package com.cans.lightning.business.lowcode.manager.form.save.handler;

import com.cans.lightning.business.lowcode.entity.AppTable;
import com.cans.lightning.business.lowcode.enums.TableTypeEnum;
import com.cans.lightning.business.lowcode.manager.AppIndexManager;
import com.cans.lightning.business.lowcode.manager.form.bean.AppFormBean;
import com.cans.lightning.business.lowcode.manager.form.bean.SonTableBean;
import com.cans.lightning.business.lowcode.manager.form.save.AbstractBeanSaveHandler;
import com.cans.lightning.business.lowcode.manager.form.save.context.AppFormDesignSaveContext;
import com.cans.lightning.business.lowcode.service.api.IAppTableService;
import com.cans.lightning.utils.StringUtils;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * formBean -- 主表信息保存入库
 *
 * @author cans
 * @date 2023/11/29
 **/
@Component
public class FormDesignSonTableSaveHandler extends AbstractBeanSaveHandler<AppFormBean> {

    @Resource
    private IAppTableService appTableService;
    @Resource
    private AppIndexManager appIndexManager;

    @Override
    public AppFormBean saveOne(AppFormDesignSaveContext<AppFormBean> saveContext) {
        AppFormBean appFormBean = saveContext.getData();
        List<AppTable> appTables = this.extractedAppTable(appFormBean);
        for (AppTable appTable : appTables) {
            appTableService.saveOrUpdate(appTable);
        }
        return appFormBean;
    }

    private List<AppTable> extractedAppTable(AppFormBean appFormBean) {
        List<SonTableBean> sonTableBeanList = appFormBean.getSonTableList();
        List<AppTable> sonTableList = Lists.newArrayList();
        for (SonTableBean sonTableBean : sonTableBeanList) {
            AppTable sonTable = new AppTable();
            sonTable.setFormId(sonTableBean.getId());
            sonTable.setTableType(TableTypeEnum.SON.getKey());
            String dbTableName = sonTable.getDbTableName();
            if(StringUtils.isEmpty(dbTableName)){
                dbTableName = appIndexManager.getNextMainTableName();
            }
            sonTable.setDbTableName(dbTableName);
            sonTable.setAppId(appFormBean.getAppId());
            sonTable.setTableName(appFormBean.getFormName());
            sonTableList.add(sonTable);
        }

        return sonTableList;

    }


}
